package com.sto.stoapp.activity.sales;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.StoBillFiterActivity;
import com.sto.stoapp.activity.StoLoginActivity;
import com.sto.stoapp.activity.administrator.system.AdminSystemSettingActivity;
import com.sto.stoapp.activity.scanner.StoBusinessSetupActivity;
import com.sto.stoapp.activity.scanner.StoDeleteWrongScanningActivity;
import com.sto.stoapp.activity.scanner.StoRecordscheckActivity;
import com.sto.stoapp.activity.scanner.StoUploadMainActivity;
import com.sto.stoapp.activity.scanner.StoYouPaiWuQianQueryActivity;
import com.sto.stoapp.adapter.SoleMainAdapter;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.broadcast.LogoutBroad;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.OrderManager;
import com.sto.stoapp.entity.FunctionEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.manager.AlarmClockManager;
import com.sto.stoapp.server.StoDownServer;
import com.sto.stoapp.service.TimingService;
import com.sto.stoapp.upload.UploadDataService;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseActivity;
import com.sto.stoapp.widget.BaseDialog;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

public class StoSalesMainActivity extends BaseActivity {

	private GridView salesMainList;

	private SoleMainAdapter soleAdapter;

	// 按键映射
	private static final int[] MAPP_TO_KEY = { R.string.record_upload,
			R.string.received_piece, R.string.sign_in, R.string.problem_piece,
		//	R.string.h_received_piece, 
			R.string.server_point_sms,
			R.string.super_limits_search, R.string.order_function,
			R.string.del_error_code, R.string.record_search };

	// private Boolean checkTimeRet=false;
	private LogoutBroad logoutBroad;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_sales_main);

//		UnSentDataManager.getInstance().setUnSent(
//				UploadDataManager.getInstance(this).getUnsendDataCount());

		this.setStoTitle(R.string.busniess_sales);
		this.register(HomeBroadAction.SALES_MAN_BROAD);
		initWidget();
		initUnsentDataCount();
		// 登入类型,用于后面业务判断是业务员或扫描员类型
		// UnifiedStaticType.loginType = BaseMessage.SALES_VERSION;
		orderIsOpen();
	}

	private void initWidget() {
		salesMainList = (GridView) findViewById(R.id.sales_main_list);
		soleAdapter = new SoleMainAdapter(this, getResourceList());
		salesMainList.setAdapter(soleAdapter);
		salesMainList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				arg1.setSelected(true);
				TextView title = (TextView) arg1.findViewById(R.id.res_test);
				clickItemEvent(title.getText().toString());
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void clickItemEvent(String title) {
		// 收件
		if (title.equals(getText(R.string.received_piece))) {
			// if (checkTimeSyn()) {
			// Intent intent = new Intent(this,
			// SalesReceivedPieceActivity.class);
			// intent.putExtra("busiType", " | ");
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(SalesReceivedPieceActivity.class, this, " | ");
		}
		// 签收
		else if (title.equals(getText(R.string.sign_in))) {
			// if (checkTimeSyn()) {
			// Intent intent = new Intent(this, SalesSignInActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(SalesSignInActivity.class, this, "");
		}
		// 问题件
		else if (title.equals(getText(R.string.problem_piece))) {
			// if (checkTimeSyn()) {
			// Intent intent = new Intent(this,
			// SalesProblemPieceActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }

			// SalesProblemPieceSelectActivity
			checkTimeSyn(SalesProblemPieceSelectActivity.class, this,
					HomeBroadAction.SALES_MAN_BROAD);
		}
		// 24小时扫描操作
		else if (title.equals(getText(R.string.h_received_piece))) {
			// if (checkTimeSyn()) {
			// Intent intent = new Intent(this,
			// SalesReceivedPieceActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// intent.putExtra("busiType", " |1"); // 24小时
			// startActivity(intent);
			// }
			checkTimeSyn(SalesReceivedPieceActivity.class, this, " |1");
		}
		// 订单功能
		else if (title.equals(getText(R.string.order_function))) {
			if (StoFilePreference.getInstance(StoSalesMainActivity.this)
					.getOrderFunctionControl()) {
				// if (checkTimeSyn()) {
				// Intent intent = new Intent(this,
				// SalesOrderFunctionActivity.class);
				// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				// startActivity(intent);
				// }
				checkTimeSyn(SalesOrderFunctionActivity.class, this, "");
			} else {
				Helper.showSoundToast(this,
						getString(R.string.order_function_no_open), false);
			}
		}
		// 服务点短信
		else if (title.equals(getText(R.string.server_point_sms))) {
			// if (checkTimeSyn()) {
			// Intent intent = new Intent(this,
			// SalesServerPointSmsActivity.class);
			// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			// startActivity(intent);
			// }
			checkTimeSyn(SalesServerPointSmsActivity.class, this,
					HomeBroadAction.SALES_MAN_BROAD);
		}
		// 无点超派范围查询
		else if (title.equals(getText(R.string.super_limits_search))) {
			Intent intent = new Intent(this, SalesWdcpQueryActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 业务员-有派无签
		else if (title.equals(getText(R.string.youpaiwuqian))) {
			Intent intent = new Intent(this, StoYouPaiWuQianQueryActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 删除错扫
		else if (title.equals(getText(R.string.del_error_code))) {
			Intent intent = new Intent(this,
					StoDeleteWrongScanningActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 记录查询
		else if (title.equals(getText(R.string.record_search))) {
			Intent intent = new Intent(this, StoRecordscheckActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 记录上传
		else if (title.equals(getText(R.string.record_upload))) {
			Intent intent = new Intent(this, StoUploadMainActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 业务设置
		else if (title.equals(getText(R.string.business_settings))) {
			Intent intent = new Intent(this, StoBusinessSetupActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 电话短信
		else if (title.equals(getText(R.string.telphone_sms))) {
			Intent intent = new Intent(this, SalesTelphoneSmsActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 系统设置
		else if (title.equals(getText(R.string.system_settings))) {
			Intent intent = new Intent(this, AdminSystemSettingActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra(HomeBroadAction.BROAD_TYPE,
					HomeBroadAction.SALES_MAN_BROAD);
			startActivity(intent);
		}
		else if(title.equals(getText(R.string.filter))){
			Intent intent=new Intent(this, StoBillFiterActivity.class);
			intent.putExtra("busiType", HomeBroadAction.SALES_MAN_BROAD);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		}
		// 用户切换
		else {
			onBackPressed();
		}
	}

	private List<FunctionEntity> getResourceList() {
		int[] picIds = { R.drawable.received_piece, R.drawable.sign_in,
				R.drawable.problem_piece, R.drawable.h_received_piece,
			//	R.drawable.h_received_piece,
				R.drawable.server_point_sms,
				R.drawable.super_limits_search, R.drawable.order_function,
				R.drawable.del_error_code, R.drawable.record_search,
				R.drawable.record_upload, R.drawable.business_settings,
				R.drawable.kai_after_sales, R.drawable.bill_filter,
				R.drawable.telphone_sms, R.drawable.system_settings,
				R.drawable.logout };
		List<String> resList = new ArrayList<String>();
		resList.add(getText(R.string.received_piece).toString());
		resList.add(getText(R.string.sign_in).toString());
		resList.add(getText(R.string.problem_piece).toString());
	//	resList.add(getText(R.string.h_received_piece).toString());
		resList.add(getText(R.string.youpaiwuqian).toString());
		resList.add(getText(R.string.server_point_sms).toString());
		resList.add(getText(R.string.super_limits_search).toString());
		resList.add(getText(R.string.order_function).toString());
		resList.add(getText(R.string.del_error_code).toString());
		resList.add(getText(R.string.record_search).toString());
		resList.add(getText(R.string.record_upload).toString());
		resList.add(getText(R.string.business_settings).toString());
		resList.add(getText(R.string.telphone_sms).toString());
		resList.add(getText(R.string.filter).toString());
		resList.add(getText(R.string.system_settings).toString());
		resList.add(getText(R.string.logout).toString());
		List<FunctionEntity> functionList = new ArrayList<FunctionEntity>();
		for (int i = 0; i < resList.size(); i++) {
			FunctionEntity entity = new FunctionEntity();
			entity.setTitle(resList.get(i));
			entity.setPicId(picIds[i]);
			functionList.add(entity);
		}
		return functionList;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		// 退出
		if (intent.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE) != null) {
			if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0
					&& intent
							.getStringExtra(AlarmClockManager.ALARM_CLOCK_TYPE)
							.equals(HomeBroadAction.ALARM_LOGOUT)) {
				// StoFilePreference.getInstance(this).clearLoginInfo();
				// StoFilePreference.getInstance(this).clearOderAndTimeSynData();
				Intent logoutIntent = new Intent(this, StoLoginActivity.class);
				startActivity(logoutIntent);
				finish();
			}
		}
	}

	/**
	 * 小退 返回网点选择状态
	 */
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
//		if (AccessControlManager.getInstance(this).getJobSelect()) {
			if (keyCode == StoPdaKeyEvent.KEYCODE_DEL) {
				startActivity(new Intent(this, StoSitePointSelectActivity.class)
						.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
				this.finish();
			}
//		}
		return super.onKeyUp(keyCode, event);
	}

	/**
	 * 退回到登入界面
	 */
	@Override
	public void onBackPressed() {
		/*
		 * new AlertDialog.Builder(this) .setTitle(R.string.prompt)
		 * .setMessage(R.string.change_user) .setPositiveButton(R.string.change,
		 * new DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * Intent intent = new Intent( StoSalesMainActivity.this,
		 * StoLoginActivity.class); startActivity(intent); finish(); } })
		 * .setNegativeButton(R.string.cancel, new
		 * DialogInterface.OnClickListener() {
		 * 
		 * @Override public void onClick(DialogInterface dialog, int which) {
		 * dialog.dismiss(); } }) .setCancelable(false).show();
		 */
		Helper.logoutAlert(this);
	}

	/**
	 * 是否开启订单
	 */
	private void orderIsOpen() {
		System.out.println("getOrderOpenStaus:"
				+ StoFilePreference.getInstance(StoSalesMainActivity.this)
						.getOrderOpenStaus());
		if (!StoFilePreference.getInstance(StoSalesMainActivity.this)
				.getOrderOpenStaus()) {
			final BaseDialog dialog = new BaseDialog(this);
			dialog.setTitles(getString(R.string.order_fun_open));
			dialog.show();
			dialog.getvMessage().setVisibility(View.GONE);
			dialog.getvPresentation().setVisibility(View.GONE);
			dialog.setOnBackClickListener(new OnBackClickListener() {

				@Override
				public void onBackClickListener(boolean res) {
					// TODO Auto-generated method stub
					if (res) {
						// StoFilePreference
						// .getInstance(StoSalesMainActivity.this)
						// .setOrderFunctionControl(res);
						// 自动下载订单广播
						// openGPSSettings();
						OrderManager.getInstance(StoSalesMainActivity.this)
								.deleteWeek();
						Intent Tintent = new Intent(
								UnifiedStaticType.TIMING_ACTION);
						Tintent.putExtra(UnifiedStaticType.TIMING_TYPE,
								UnifiedStaticType.AUTO_DOWNLOAD_ORDER_TIMING);
						sendBroadcast(Tintent);
					}
					System.out.println("order");
					StoFilePreference.getInstance(StoSalesMainActivity.this)
							.setOrderFunctionControl(res);
					dialog.dismiss();
				}
			});
			StoFilePreference.getInstance(StoSalesMainActivity.this)
					.setOrderOpenStaus(true);
		}
	}

	/**
	 * 自动打开GPS
	 * 
	 * @modify mgf
	 */
	private void openGPSSettings() {
		// 获取GPS现在的状态（打开或是关闭状态）
		boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
				getContentResolver(), LocationManager.GPS_PROVIDER);
		if (!gpsEnabled) {
			Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
			startActivity(intent);
		}
	}

	/**
	 * 时间同步检测
	 * 
	 * @param c
	 * @param type
	 */
	private void checkTimeSyn(final Class<?> c, final Context context,
			final String type) {
		if (!(StoFilePreference.getInstance(StoSalesMainActivity.this)
				.getsetTimeSynch())) {
			final BaseDialog dialog = new BaseDialog(this);
			dialog.setTitles(getString(R.string.synch_time_hint));
			dialog.show();
			dialog.setOnBackClickListener(new OnBackClickListener() {

				@Override
				public void onBackClickListener(boolean res) {
					// TODO Auto-generated method stub
					dialog.dismiss();
					if (res) {
						Intent intent = new Intent(context, c);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						intent.putExtra("busiType", type);
						startActivity(intent);
					}
				}
			});
		} else {
			Intent intent = new Intent(context, c);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			intent.putExtra("busiType", type);
			this.startActivity(intent);
		}
	}

	/**
	 * 注册广播
	 * 
	 * @param action
	 *            事件
	 */
	public void register(String action) {
		IntentFilter filter = new IntentFilter(action);
		logoutBroad = new LogoutBroad();
		registerReceiver(logoutBroad, filter);
	}

	/**
	 * 注销广播
	 */
	private void unRegister() {
		if (logoutBroad != null) {
			unregisterReceiver(logoutBroad);
		}
	}

	@Override
	protected void onDestroy() {
		// 退出的时候关闭后台服务
		System.out.println("onDestroy sales");
		unRegister();
		if (!UnifiedStaticType.NOT_CLOSE) {
			StoFilePreference.getInstance(StoSalesMainActivity.this)
					.clearOderAndTimeSynData();
			stopService(new Intent(this, StoDownServer.class));
			stopService(new Intent(this, UploadDataService.class));
			stopService(new Intent(this, TimingService.class));
		}
		UnifiedStaticType.NOT_CLOSE = false;

		super.onDestroy();
	}

//	/**
//	 * 按键映射 数字键0~9映射（0表示列表第十条数据）
//	 */
//	@Override
//	public boolean onKeyDown(int keyCode, KeyEvent event) {
//		if (keyCode >= KeyEvent.KEYCODE_0 && keyCode <= KeyEvent.KEYCODE_9) {
//			clickItemEvent(getString(MAPP_TO_KEY[keyCode - KeyEvent.KEYCODE_0]));
//		}
//		return super.onKeyDown(keyCode, event);
//	}

}
